import 'package:flutter/material.dart';

///拖动回调
class SlideCallback extends StatefulWidget {
  const SlideCallback({
    Key? key,
    required this.child,
    this.slideToLeft,
    this.slideToRight,
    this.slideToTop,
    this.slideToBottom,
    this.onTap,
    this.onDoubleTap,
  }) : super(key: key);

  final Widget child;

  final Function()? slideToLeft;
  final Function()? slideToRight;
  final Function()? slideToTop;
  final Function()? slideToBottom;
  final Function()? onTap;
  final Function()? onDoubleTap;

  @override
  _SlideCallbackState createState() => _SlideCallbackState();
}

class _SlideCallbackState extends State<SlideCallback> {
  Offset _start = Offset.zero;
  Offset _offset = Offset.zero;

  void _onDragStart(DragStartDetails details) {
    _start = details.globalPosition;
  }

  void _onDragUpdate(DragUpdateDetails details) {
    _offset = details.globalPosition;
  }

  void _onDragEnd(DragEndDetails details) {
    final Offset end = _offset - _start;
    if (end.dx.abs() > end.dy.abs()) {
      //水平拖拽
      if (end.dx > 0) {
        //往右
        widget.slideToRight?.call();
      } else {
        //往左
        widget.slideToLeft?.call();
      }
    } else {
      //垂直拖拽
      if (end.dy > 0) {
        //往右
        widget.slideToBottom?.call();
      } else {
        //往左
        widget.slideToTop?.call();
      }
    }
  }

  void _onDragCancel() {}

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onHorizontalDragStart: _onDragStart,
      onHorizontalDragUpdate: _onDragUpdate,
      onHorizontalDragEnd: _onDragEnd,
      onHorizontalDragCancel: _onDragCancel,
      onVerticalDragStart: _onDragStart,
      onVerticalDragUpdate: _onDragUpdate,
      onVerticalDragEnd: _onDragEnd,
      onVerticalDragCancel: _onDragCancel,
      onTap: widget.onTap,
      onDoubleTap: widget.onDoubleTap,
      child: widget.child,
    );
  }
}
